package com.bawan.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.util.Properties;

/**
 * Desc:  Properties文件读写工具类
 * Author: zhengcongchun
 * CreateTime: 2014-04-01 10:13
 * LastModifyTime: 2014-04-01 10:13
 * FinalModifier: zhengcongchun
 * Version: 1.0
 */
public class PropertiesUtil {
    private static Log log = LogFactory.getLog(PropertiesUtil.class);

    /**配置文件信息加载后的数据对象**/
    private Properties properties = new Properties();

    private static PropertiesUtil instance = new PropertiesUtil();
    private PropertiesUtil() {
        try {
            InputStream in = this.getClass().getResourceAsStream("/baseConfig.properties");
            properties.load(in);
            in.close();
        } catch (IOException ioe) {
            log.error("PropertiesUtil初始化加载配置文件时报错：" + ioe.getMessage(), ioe);
        }
    }

    public PropertiesUtil getInstance() {
        if (instance == null) {
            instance = new PropertiesUtil();
        }
        return instance;
    }

    /**
     * 根据Key获得对应的配置值
     * @param key
     * @return
     */
    public String getProperty(String key) {
        if (instance == null) {
            instance = new PropertiesUtil();
        }

        return properties.getProperty(key);
    }

    /**
     * 将新的配置信息写入到原始的配置文件中
     * @param key
     * @param value
     */
    public void writeProperty(String key, String value) {
        if (key == null || "".equalsIgnoreCase(key)) {
            return;
        }
        try {
            String propertiesFilePath = this.getClass().getResource("/").toString().replace("file:/", "") + "baseConfig.properties";
            OutputStream out = new FileOutputStream(propertiesFilePath, true);
            properties.put(key, value);
            properties.store(out, "更新配置文件信息：[key:" + key + ", value:" + value + "]");
        } catch (FileNotFoundException fnfe) {
            log.error("PropertiesUtil更新配置信息加载配置文件时报错：" + fnfe.getMessage(), fnfe);
        } catch (IOException ioe) {
            log.error("PropertiesUtil更新配置信息写入到配置文件时报错：" + ioe.getMessage(), ioe);
        }
    }

    /**
     * 将新的配置信息写入到指定的配置文件中
     * @param key
     * @param value
     * @param propertiesFilePath
     */
    public void writeProperty(String key, String value, String propertiesFilePath) {
        if (key == null || "".equalsIgnoreCase(key)) {
            return;
        }
        try {
            OutputStream out = new FileOutputStream(propertiesFilePath, true);
            properties.put(key, value);
            properties.store(out, "更新配置文件信息：[key:" + key + ", value:" + value + "]");
        } catch (FileNotFoundException fnfe) {
            log.error("PropertiesUtil更新配置信息加载配置文件时报错：" + fnfe.getMessage(), fnfe);
        } catch (IOException ioe) {
            log.error("PropertiesUtil更新配置信息写入到配置文件时报错：" + ioe.getMessage(), ioe);
        }
    }
}
